package xworker.netty.handlers.message;

import org.xmeta.ActionContext;
import org.xmeta.ActionException;
import org.xmeta.Thing;
import org.xmeta.cache.ThingEntry;
import xworker.lang.executor.Executor;

public class MessageHandlers {
    HandlerManager handlerManager;
    ActionContext actionContext;
    ThingEntry thingEntry;

    public MessageHandlers(HandlerManager handlerManager, Thing thing, ActionContext actionContext){
        this.handlerManager = handlerManager;
        this.actionContext = actionContext;
        this.thingEntry = new ThingEntry(thing);

        handlerManager.addMessageHandlers(this);
        init(thing);
    }

    public void checkInit(){
        if(thingEntry.isChanged()){
            init(thingEntry.getThing());
        }
    }

    public void init(Thing thing){
        for(Thing child : thing.getChilds()){
            if(child.isThingByName("MessageHandler")){
                String request = child.doAction("getRequest", handlerManager.actionContext);
                if(request != null && !request.isEmpty()){
                    handlerManager.regist(request, child);
                }
            }else if(child.isThingByName("MessageHandlerRegistor")){
                child.doAction("initHandlers", actionContext, "handlerManager", handlerManager);
            }else{
                init(child, handlerManager);
            }
        }
    }

    //xworker.netty.handlers.message.MessageHandlers/@actions/@initHandlers
    public static void initHandlers(ActionContext actionContext){
        HandlerManager handlerManager = actionContext.getObject("handlerManager");
        Thing self = actionContext.getObject("self");

        new MessageHandlers(handlerManager, self, actionContext);
    }

    private static void init(Thing thing, HandlerManager handlerManager){
        if(handlerManager == null){
            throw new ActionException("HandlerManager is null");
        }

        for(Thing child : thing.getChilds()){
            if(child.isThingByName("MessageHandler")){
                String request = child.doAction("getRequest", handlerManager.actionContext);
                if(request != null && !request.isEmpty()){
                    handlerManager.regist(request, child);
                }
            }else{
                init(child, handlerManager);
            }
        }
    }

    //xworker.netty.handlers.message.MessageHandlers/@MessageHandler/@actions/@handleMessage
    public static void handleMessage(ActionContext actionContext){
        Thing self = actionContext.getObject("self");
        Executor.info(self.getMetadata().getPath(), "Should implement handleMessage method, msg=" + actionContext.getObject("msg"));
    }

    //xworker.netty.handlers.message.MessageHandlers/@GroovyMessageHandler/@actions/@handleMessage
    public static void handleGroovyMessage(ActionContext actionContex){
        Thing self = actionContex.getObject("self");
        self.getAction().run(actionContex);
    }

}

